package com.fairylove.rpc.transport.socket.server;

import com.fairylove.rpc.entity.RpcRequest;
import com.fairylove.rpc.entity.RpcResponse;
import com.fairylove.rpc.handler.RequestHandler;
import com.fairylove.rpc.serializer.CommonSerializer;
import com.fairylove.rpc.transport.utils.ObjectReader;
import com.fairylove.rpc.transport.utils.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 创建服务端执行任务
 */
public class SocketRequestHandlerRunnable implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(SocketRequestHandlerRunnable.class);

    private Socket socket;
    private RequestHandler requestHandler;
    private CommonSerializer serializer;

    public SocketRequestHandlerRunnable(Socket socket,RequestHandler requestHandler,CommonSerializer serializer){
        this.socket = socket;
        this.requestHandler = requestHandler;
        this.serializer = serializer;
    }
    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            RpcRequest request = (RpcRequest)ObjectReader.readObject(inputStream);

            Object result = requestHandler.handler(request);
            logger.info("result:{}",result );
            //对返回结果进行封装
            RpcResponse<Object> rpcResponse = RpcResponse.success(result);
            ObjectWriter.writeObject(outputStream, rpcResponse, serializer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
